package org.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.backend.bean.Category;
import org.example.backend.common.Result;
import org.example.backend.mapper.CategoryMapper;
import org.example.backend.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 啊昌
 * @date 2025/7/19 23:20
 * CategoryServiceImpl 分类实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    
    @Override
    public Result<Map<String, Object>> getCategory(String parent_id) {
        // 创建结果集
        Map<String, Object> resultMap = new HashMap<>();
        
        // 查询所有分类
        List<Category> allCategories = categoryMapper.selectList(null);
        
        // 根据parent_id参数过滤
        if (StringUtils.hasText(parent_id)) {
            try {
                // 如果指定了父分类ID，只返回该父分类下的子分类
                Integer parentIdInt = Integer.parseInt(parent_id);
                
                // 过滤出当前父分类
                Category parentCategory = allCategories.stream()
                    .filter(c -> c.getCategoryId().equals(parentIdInt))
                    .findFirst()
                    .orElse(null);
                
                if (parentCategory != null) {
                    // 过滤出该父分类下的直接子分类
                    List<Category> children = allCategories.stream()
                        .filter(c -> parentIdInt.equals(c.getParentId()))
                        .sorted(Comparator.comparingInt(Category::getSortOrder))
                        .collect(Collectors.toList());
                    
                    parentCategory.setChildren(children);
                    resultMap.put("category", parentCategory);
                } else {
                    resultMap.put("category", null);
                    resultMap.put("message", "未找到指定的父分类");
                }
            } catch (NumberFormatException e) {
                resultMap.put("error", "父分类ID必须是一个整数");
                return Result.error("父分类ID必须是一个整数");
            }
        } else {
            // 未指定父分类ID，返回完整的树形结构
            List<Category> categoryTree = buildTree(allCategories);
            resultMap.put("categories", categoryTree);
        }
        
        return Result.success(resultMap);
    }

    public static List<Category> buildTree(List<Category> categories) {
        // 按父ID分组
        Map<Integer, List<Category>> childrenMap = categories.stream()
                .filter(c -> c.getParentId() != null)
                .collect(Collectors.groupingBy(Category::getParentId));

        // 设置子节点
        categories.forEach(category -> {
            List<Category> children = childrenMap.get(category.getCategoryId());
            if (children != null) {
                // 按排序值排序
                children.sort(Comparator.comparingInt(Category::getSortOrder));
                category.setChildren(children);
            }
        });

        // 返回根节点（parentId为null）
        return categories.stream()
                .filter(c -> c.getParentId() == null)
                .sorted(Comparator.comparingInt(Category::getSortOrder))
                .collect(Collectors.toList());
    }
}
